<template>
    <div class="marketing_group_detail_statistics">
        <h1>
            数据概览
            <el-tooltip effect="dark" placement="right">
                <template #content>
                    已领取：优惠券领取张数。<br />
                    已使用：优惠券使用张数。使用后退款导致优惠券退回，使用张数回退。<br />
                    剩余：优惠券剩余库存量。<br />
                    用券支付金额：使用该优惠券的订单成功支付的金额。订单关闭后，用券支付金额扣除。<br />
                    用券笔单价：用券支付金额/用券支付订单数。订单关闭后，用券支付订单数扣除。<br />
                </template>
                <el-icon><Warning /></el-icon>
            </el-tooltip>
        </h1>
        <el-row class="preview-custom-row">
            <el-col
                v-for="{ label, prop } in totalCols"
                :key="label"
                class="preview-custom-col"
                :span="prop === 'couponPerCustomerPrice' ? 4 : 5">
                <span>{{ statisticBasic[prop] }}</span>
                <span>{{ label }}</span>
            </el-col>
        </el-row>
        <div class="tab-search">
            <el-radio-group v-model="tabRadio" @change="tabRadioChange">
                <el-radio-button :label="1">领取记录</el-radio-button>
                <el-radio-button :label="2">使用记录</el-radio-button>
            </el-radio-group>
            <el-form class="statistics-coupon-form" ref="formRef" :model="form" @submit.prevent>
                <template v-if="tabRadio == 1">
                    <el-form-item prop="keywords" class="mr8">
                        <el-input
                            class="w240"
                            v-model="form.keywords"
                            clearable
                            placeholder="客户姓名/手机号"></el-input>
                    </el-form-item>
                    <el-form-item prop="keywords" class="mr8">
                        <el-select class="w240" v-model="form.status" placeholder="全部状态">
                            <el-option
                                v-for="item in couponStatusList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </template>
                <template v-else>
                    <el-form-item prop="keywords" class="mr8">
                        <el-input
                            class="w240"
                            v-model="form.keywords"
                            clearable
                            placeholder="客户姓名/手机号/用券订单号"></el-input>
                    </el-form-item>
                </template>
                <div class="ml24">
                    <el-button type="primary" @click="searchHandler">查询</el-button>
                    <!-- <el-button plain @click="resetHandler">清空</el-button> -->
                </div>
                <div class="export-btn">
                    <el-button plain @click="handleExport" v-auth="'coupon_list:export'">导出</el-button>
                    共{{ totalCount || 0 }}条数据
                </div>
            </el-form>
        </div>
        <!-- 列表 -->
        <el-table :data="tableList" :key="tabRadio" :stripe="true" class="statistics-table">
            <el-table-column
                v-for="{ prop, label, width, ...rest } in tableColumns"
                :key="prop"
                :label="label"
                :prop="prop"
                :width="width || 'auto'"
                v-bind="rest">
                <template #default="{ row }">
                    <template v-if="prop == 'orderSn'">
                        <!-- <el-link type="primary" class="custom-el-link" @click="nameRouteHandler(row)">{{
                            row.orderSn
                        }}</el-link> -->
                        <div class="custom-el-link">
                            <span @click="nameRouteHandler(row)">{{ row.orderSn }}</span>
                        </div>
                    </template>
                    <template v-if="prop === 'couponStatusName'">
                        <span :class="`custom-status-${row.couponStatus}`">{{ row.couponStatusName }}</span>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="margin-top: 15px">
            <Pagination
                :total="totalCount"
                :page-size="form.perPage"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
    </div>
</template>

<script setup>
import { ref, unref, reactive, onMounted, computed } from 'vue';
import constants from '@/commons/constants';
import { useRouter } from 'vue-router';
import { packSelectObjUtil, exportExc, format, cloneDeep, floatDivide } from '@/commons/utils';
import request from '@/request/index';
import { debounce } from 'lodash';
import Pagination from '@/components/Pagination.vue';

const couponStatusList = reactive(packSelectObjUtil(constants.COUPON_STATUS_STATISTICS_OPTIONS));

const router = useRouter();

const props = defineProps(['info']);

const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10, //页记录数
    keywords: '', //搜索关键字
    status: 0
});
const formClone = cloneDeep(form);
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = computed(() => {
    if (tabRadio.value == 1) {
        return [
            { label: '客户', prop: 'userNameText', showOverflowTooltip: true },
            { label: '使用状态', prop: 'customerCouponName' },
            { label: '领取时间', prop: 'createdAt', sortable: true }
        ];
    } else {
        return [
            { label: '客户', prop: 'userNameText', showOverflowTooltip: true },
            { label: '用券订单号', prop: 'orderSn', showOverflowTooltip: true },
            { label: '使用时间', prop: 'useAt', sortable: true }
        ];
    }
});
let statisticBasic = reactive({
    couponAcquiredNumber: 0,
    couponUsedNumber: 0,
    couponSurplusNumber: 0,
    couponPaidNumber: 0,
    couponPerCustomerPrice: 0
});

const totalCols = computed(() => {
    const cols = [
        { label: '已领取（张）', prop: 'couponAcquiredNumber' },
        { label: '已使用（张）', prop: 'couponUsedNumber' },
        { label: '剩余（张）', prop: 'couponSurplusNumber' },
        { label: '用券支付金额（元）', prop: 'couponPaidNumber' },
        { label: '用券笔单价（元）', prop: 'couponPerCustomerPrice' }
    ];
    return cols;
});

let tabRadio = ref(1);
const tabRadioChange = () => {
    Object.assign(form, formClone);
    tableList.length = 0;
    queryCouponListHandler();
};
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const { status, ...rest } = form;
    let res;
    if (tabRadio.value == 1) {
        // 领取记录
        res = await request('couponRecord', { id: props?.info?.id, ...form });
    } else {
        // 使用记录
        res = await request('couponUseRecord', { id: props?.info?.id, ...rest });
    }
    const list = (res?.data.list || []).map(item => {
        if (item.userName && item.mobile) {
            item.userNameText = `${item.userName}（${item.mobile}）`;
        } else if (item.userName) {
            item.userNameText = item.userName;
        } else if (item.mobile) {
            item.userNameText = item.mobile;
        } else {
            item.userNameText = '-';
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res?.data.totalCount;
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
};

const nameRouteHandler = row => {
    const { href } = router.resolve({
        path: '/order/list/detail',
        query: {
            orderId: row.orderId
        }
    });
    window.open(href, '_blank');
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryCouponListHandler();
};

const handleExport = debounce(async () => {
    let res;
    const { status, ...rest } = form;
    if (tabRadio.value == 1) {
        res = await request('couponRecordExport', {
            id: props?.info?.id,
            ...form,
            perPage: unref(totalCount)
        });
    } else {
        res = await request('couponUseRecordExport', {
            id: props?.info?.id,
            ...rest,
            perPage: unref(totalCount)
        });
    }
    const exportText = tabRadio.value == 1 ? '_领取记录_' : '使用记录';
    exportExc(res, props?.info?.couponName + exportText + format(new Date(), 'YYYY-MM-DD_HH.mm.ss'));
}, 500);

const getStatisticBasic = async () => {
    const { data } = await request('couponData', { id: props?.info?.id });
    const dataCopy = data || {};
    // couponAcquiredNumber已领取 couponUsedNumber已使用 couponPerCustomerPrice笔单价 couponPaidNumber支付金额
    dataCopy.couponAcquiredNumber = dataCopy?.couponAcquiredNumber || 0;
    dataCopy.couponUsedNumber = dataCopy?.couponUsedNumber || 0;
    dataCopy.couponSurplusNumber = dataCopy?.couponSurplusNumber || 0;
    dataCopy.couponPaidNumber = floatDivide(dataCopy?.couponPaidNumber || 0, 100);
    dataCopy.couponPerCustomerPrice = floatDivide(dataCopy?.couponPerCustomerPrice || 0, 100);
    Object.assign(statisticBasic, dataCopy);
};

const getAllData = () => {
    getStatisticBasic();
    searchHandler();
};

onMounted(() => {
    getAllData();
});
</script>

<style lang="scss" scoped>
$colors: #cccccc, #ff6b00, #ffd500;

.marketing_group_detail_statistics {
    .custom-status-tip {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
    }
    h1 {
        font-size: 14px;
        font-weight: 500;
        position: relative;
        padding-left: 15px;
        margin: 0;
        margin-top: 10px;
        display: flex;
        align-items: center;
        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 15%;
            width: 3px;
            height: 70%;
            background-color: var(--el-color-primary);
        }
        &:last-of-type {
            margin-bottom: 16px;
        }
        :deep(.el-icon) {
            color: #33302d;
            margin-left: 4px;
        }
    }
    .preview-custom-row {
        margin: 30px 0;
    }
    .preview-custom-col {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        flex-direction: column;
        /* & + div {
            border-left: 1px solid #eee;
        } */
        span {
            font-size: 24px;
            font-family: HelveticaNeue-Medium, HelveticaNeue;
            font-weight: 500;
            color: #333333;
            margin-bottom: 7px;
            & + span {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
            }
        }
    }

    .zw-form-btns {
        display: flex;
    }

    .zw-form-layout {
        background-color: #fff;
        border: 0;
        padding: 0;
    }

    .export-btn {
        color: #969696;
        font-size: 14px;
        margin-left: 8px;
    }

    :deep {
        .statistics-table .el-table__cell {
            padding: 20px 0;
        }
        .el-table th.el-table__cell {
            padding: 12px 0;
        }
        .statistics-table .el-table__expanded-cell {
            background: #f9f9f9;
            padding: 0;
            &:hover {
                background: #f9f9f9 !important;
            }
        }
        .el-table {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
        }
        .el-table th.el-table__cell {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #33302d;
        }
    }
    .custom-el-link {
        color: rgb(255, 107, 0);
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        span {
            cursor: pointer;
            &:hover {
                text-decoration: underline;
            }
        }
    }
    @for $i from 1 to 4 {
        .custom-status-#{$i} {
            position: relative;
            padding-left: 14px;
            &::before {
                content: '';
                position: absolute;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                left: 0px;
                top: 50%;
                transform: translateY(-50%);
                background: nth($colors, $i);
            }
        }
    }

    .tab-search {
        display: flex;
        justify-content: space-between;
        margin-bottom: 18px;
        .w240 {
            width: 240px;
        }
        .ml24 {
            margin-left: 24px;
        }
        .mr8 {
            margin-right: 8px;
        }
        :deep {
            .el-radio-button__inner {
                background: #ffffff;
                border: 1px solid #eaeaea;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
            }
            .el-radio-button__original-radio:checked + .el-radio-button__inner {
                color: #ff6b00;
                font-weight: 500;
                border: 1px solid #ff6b00;
            }
            .el-input__wrapper {
                box-shadow: 0 0 0 1px #eaeaea inset;
            }
        }
    }
    .statistics-coupon-form {
        display: flex;
        align-items: center;
        :deep {
            .el-form-item {
                margin-bottom: 0;
            }
        }
    }
}
</style>
